package com.twotwoshop.service.goods.service.Impl;

import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twotwoshop.commom.redis.RedisConstants;
import com.twotwoshop.domin.common.dtos.PageResponseResult;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.goods.pojo.Product;
import com.twotwoshop.domin.goods.vos.ProductVo;
import com.twotwoshop.domin.user.pojos.ApUser;
import com.twotwoshop.fegin.api.user.IUserClient;
import com.twotwoshop.service.goods.mapper.ProductMapper;
import com.twotwoshop.service.goods.service.BrowsingHistoryService;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class BrowsingHistoryServiceImpl implements BrowsingHistoryService {

    private final StringRedisTemplate stringRedisTemplate;

    private final ProductMapper productMapper;

    private final IUserClient userClient;


    /**
     * 记录用户对商品的浏览
     *
     * @param userId
     * @param productId
     */
    @Override
    @Async("twotwoShopGoodsExecutor")
    public void addBrowsingHistory(Integer userId, Long productId) {

        log.info("addBrowsingHistory浏览历史添加成功");

        //1.参数判空
        if (userId == null || productId == null) {
            throw new IllegalArgumentException("userId and productId cannot be null");
        }

        //2.保存浏览历史  key + userId 拼成     商品id作为成员  当前时间当作score
        stringRedisTemplate.opsForZSet().add(RedisConstants.GOODS_VIEWS_HISTORY_KEY + userId.toString(), productId.toString(), System.currentTimeMillis());

    }


    /**
     * 获取浏览历史
     *
     * @return
     */
    @Override
    public ResponseResult getViewsHistory() {

        //1.获取用户id
        Integer id = AppThreadLocalUtil.getUser().getId();

        // 2. 从Redis中获取用户浏览历史
        Set<String> goodsViewHistory = stringRedisTemplate.opsForZSet().rangeByScore(RedisConstants.GOODS_VIEWS_HISTORY_KEY + id.toString(), 0D, Double.MAX_VALUE);

        // 3. 检查是否有浏览历史
        if (goodsViewHistory == null || goodsViewHistory.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }


        // 4.根据集合查询全部浏览过的商品
        List<Product> products = productMapper.selectBatchIds(goodsViewHistory);

        List<ProductVo> vos=new ArrayList<>();

        for (Product product : products) {

            ProductVo vo = new ProductVo();
            BeanUtils.copyProperties(product, vo);

            //将图片路径转化为集合
            List<String> imageList = Arrays.stream(product.getImages().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());

            vo.setImages(imageList);

            //查询发布商品人的昵称和头像
            ResponseResult userInfo = userClient.getUserInfoById(product.getUserId());
            if (userInfo.getCode()==200){
                //拿取用户信息
                String jsonString = JSONUtil.toJsonStr(userInfo.getData());
                ApUser user = JSONUtil.toBean(jsonString, ApUser.class);

                //设置用户的名称和头像
                vo.setName(user.getName());
                vo.setImage(user.getImage());
                vo.setUserId(user.getId().longValue());
            }

            vos.add(vo);

        }



        // 4. 返回浏览历史记录
        return ResponseResult.okResult(vos);
    }


    /**
     * 清空浏览历史
     *
     * @return
     */
    @Override
    public ResponseResult clearViewsHistory() {

        //1.获取用户id
        Integer id = AppThreadLocalUtil.getUser().getId();

        // 2. 从Redis中获取用户浏览历史
        Set<String> goodsViewHistory = stringRedisTemplate.opsForZSet().rangeByScore(RedisConstants.GOODS_VIEWS_HISTORY_KEY + id.toString(), 0D, Double.MAX_VALUE);

        if (goodsViewHistory == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 2. 从Redis中删除
        Boolean delete = stringRedisTemplate.delete(RedisConstants.GOODS_VIEWS_HISTORY_KEY + id.toString());

        // 3. 检查是否有浏览历史
        if (!delete) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"删除失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
















